/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.SalesBP;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import managedbean.Workspace.FileUploadManagerBean;
import merlion.common.entity.Staff;
import merlion.common.util.Consts;
import merlion.crm.slcm.entity.ContactRecord;
import merlion.frm.bpm.entity.CustomerPaymentRecord;
import merlion.frm.bpm.entity.Invoice;
import merlion.frm.bpm.entity.Receipt;
import merlion.frm.bpm.session.SalesBPSessionBeanLocal;
import merlion.mrp.atpm.session.ATPSessionBeanLocal;
import merlion.scm.lcm.entity.DeliveryOrder;
import merlion.scm.lcm.session.LogisticControlSessionBeanLocal;

/**
 *
 * @author Kenn & Zhou Hong
 */
@ManagedBean(name = "cprManagerBean")
@ViewScoped
public class CustomerPaymentRecordManagerBean {

    @EJB
    private SalesBPSessionBeanLocal sbpSessionBean;
    private CustomerPaymentRecord cpr;
    private CustomerPaymentRecord selectedCpr;
    private Receipt receipt;
    private String statusMsg;
    private Staff loginUser;
    private Collection<CustomerPaymentRecord> cprs;
    private Collection<Receipt> receipts;
    @EJB
    private ATPSessionBeanLocal atpSessionBean;
    @EJB
    private LogisticControlSessionBeanLocal lcSessionBean;
    @ManagedProperty(value = "#{fileUploadManagerBean}")
    private FileUploadManagerBean fileManagerBean;

    //--------------------------------------------------------------------------
    //                              Constructor
    //--------------------------------------------------------------------------
    public CustomerPaymentRecordManagerBean() {
    }

    @PostConstruct
    public void init() {

        loginUser = (Staff) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("app.user.name");
        cpr = (CustomerPaymentRecord) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("cpr");
        receipt = (Receipt) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("receipt");
        statusMsg = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("statusMsg");

        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("cpr");
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("receipt");
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("statusMsg");

        if (cpr == null) {
            cpr = new CustomerPaymentRecord();
            cpr.setCustomerPaymentRecordId(sbpSessionBean.generateCustomerPaymentRecordId());
            cpr.setInvoice(new Invoice());
            cpr.setPaymentDate(new Timestamp(System.currentTimeMillis()));
        }

    }

    //--------------------------------------------------------------------------
    //                CustomerPaymentRecordManagerBean Methods
    //--------------------------------------------------------------------------    
    public String createReceipt() {

        //Validate
        boolean valid = true;
        if (cpr.getPaymentMethod() == null || cpr.getPaymentMethod().equals("")) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Payment Method cannot be empty", ""));
            valid = false;
        }
        if ((double) cpr.getPaymentAmount() == 0) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Payment amount cannot be zero", ""));
            valid = false;
        }
        if (cpr.getPaymentAmount().longValue() != cpr.getInvoice().getTotal().longValue()) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Full exact payment must be made", ""));
            valid = false;
        }

        if (valid) {

            cpr.setPaymentAmount(cpr.getInvoice().getTotal());
            cpr.setAmountDue(cpr.getInvoice().getTotal());
            receipt = new Receipt();
            receipt.setReceiptId(sbpSessionBean.generateReceiptId());
            receipt.setCustomerPaymentRecord(cpr);
            receipt.setDeliveryOrder(cpr.getInvoice().getDeliveryOrder());
            receipt.setFinanceAccountant(loginUser.getFirstName() + " " + loginUser.getLastName());

            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("cpr", cpr);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("receipt", receipt);

            return "createCustomerPaymentRecordReceipt?faces-redirect=true";
        }

        return null;
    }
    
    public void setRefunded(){
        sbpSessionBean.refund(cpr);
    }

    public String cancel() {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("statusMsg", "Create Customer Payment Record / Receipt cancelled");
        return "viewCustomerPaymentRecordStatus?faces-redirect=true";
    }

    public String saveReceipt() {
        cpr.getInvoice().setPaid(true);
        if(cpr.getInvoice().getCashInAdvance() == false){
            cpr.setRealPayment(Boolean.TRUE);
        }
        cpr = sbpSessionBean.saveCustomerPaymentRecord(cpr);
        receipt.setCustomerPaymentRecord(cpr);
        receipt = sbpSessionBean.saveReceipt(receipt);


        if (cpr != null && receipt != null) {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("statusMsg", "Customer Payment Record and Receipt created successfully.");

            //TO DO:
            if (cpr.getCashInAdvance().booleanValue() == true) {
                List<DeliveryOrder> dList;
                DeliveryOrder d = cpr.getInvoice().getDeliveryOrder();
                //Check whether the salesOrder's another deliveryOrder's invoice is paid
                dList = (List<DeliveryOrder>) d.getSalesOrder().getDeliveryOrders();
                boolean can = true;
                DeliveryOrder d2 = null;
                if (dList.size() == 2) {
                    for (int i = 0; i < dList.size(); i++) {
                        d2 = dList.get(i);
                        if (d2.getDeliveryOrderIdStr().equals(d.getDeliveryOrderIdStr())) {
                        } else {
                            break;
                        }
                    }

                    if (d2.getInvoice().getCustomerPaymentRecord() == null) {
                        can = false;
                    }
                }

                if (can) {
                    d.getSalesOrder().setSalesOrderStatus(Consts.ORDER_ATPCHECKING);
                    System.out.println("Customer Payment Record ManagerBean: call ATP for deliveryOrder: " + d.getDeliveryOrderIdStr());
                    if (d.getIndicativeLeadTimeTS() != null) {
                        atpSessionBean.getConfirmedLeadTime(d, d.getIndicativeLeadTimeTS());
                    }
                    if (dList.size() == 2) {
                        System.out.println("Customer Payment Record ManagerBean: partial shipping - call ATP for deliveryOrder: " + d2.getDeliveryOrderIdStr());
                        atpSessionBean.getConfirmedLeadTime(d2, d2.getIndicativeLeadTimeTS());
                    }
                }
            }


//                 if(d.getIndicativeLeadTime().equals("Available")){
//                     d.getSalesOrder().setSalesOrderStatus(Consts.ORDER_WAITING_CONFIRMATION);
//                 }
//                 if(d.getIndicativeLeadTime().equals("Pending")){
//                     d.getSalesOrder().setSalesOrderStatus(Consts.ORDER_ATPPENDING);
//                 }
            //lcSessionBean.saveDeliveryOrder(d);
        } else {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("statusMsg", "Transaction to create Customer Payment Record and Receipt has failed. Please try again.");
        }


        return "viewCustomerPaymentRecordStatus?faces-redirect=true";
    }

    public String viewCustomerPaymentRecord() {
        cpr = selectedCpr;
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("cpr", cpr);
        return "viewCustomerPaymentRecordDisplay?faces-redirect=true";
    }

    public String editCustomerPaymentRecord() {
        return null;
    }

    public String closeCustomerPaymentRecord() {
        return null;
    }

    public String viewReceipt() {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("receipt", receipt);
        return "viewReceiptDisplay?faces-redirect=true";
    }

    public Collection<Invoice> getAllUnpaidInvoice() {
        return sbpSessionBean.getAllUnpaidInvoice();
    }

    //--------------------------------------------------------------------------
    //                          Getter and Setter
    //--------------------------------------------------------------------------
    public CustomerPaymentRecord getCpr() {
        return cpr;
    }

    public void setCpr(CustomerPaymentRecord cpr) {
        this.cpr = cpr;
    }

    public String getStatusMsg() {
        return statusMsg;
    }

    public void setStatusMsg(String statusMsg) {
        this.statusMsg = statusMsg;
    }

    public Receipt getReceipt() {
        return receipt;
    }

    public void setReceipt(Receipt receipt) {
        this.receipt = receipt;
    }

    public Collection<CustomerPaymentRecord> getCprs() {
        return sbpSessionBean.getAllCustomerPaymentRecord();
    }

    public void setCprs(Collection<CustomerPaymentRecord> cprs) {
        this.cprs = cprs;
    }

    public Collection<Receipt> getReceipts() {
        return sbpSessionBean.getAllReceipt();
    }

    public void setReceipts(Collection<Receipt> receipts) {
        this.receipts = receipts;
    }

    public CustomerPaymentRecord getSelectedCpr() {
        return selectedCpr;
    }

    public void setSelectedCpr(CustomerPaymentRecord selectedCpr) {
        this.selectedCpr = selectedCpr;
    }
    
    // send email , edited by zy Nov 9
    public String sendReceiptToCustomer() {
        // edited by ZY, 9 Nov 2011
        String res = "receipt sent to supplier";
        String emailAddress = "";
        
        if (receipt == null
                || receipt.getCustomerPaymentRecord() == null 
                || receipt.getCustomerPaymentRecord().getInvoice() == null
                || receipt.getCustomerPaymentRecord().getInvoice().getCustomer() == null 
                || receipt.getCustomerPaymentRecord().getInvoice().getCustomer().getContactRecords() == null 
                || receipt.getCustomerPaymentRecord().getInvoice().getCustomer().getContactRecords().isEmpty()){
        
            res = "receipt is not able to sent to customer because no contact record is found.";
            System.out.println(res);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Sent unsuccessfully", "sent unsuccessfully"));
        } else {
            emailAddress = new ArrayList<ContactRecord>(receipt.getCustomerPaymentRecord().getInvoice().getCustomer().getContactRecords()).get(0).getEmail();
            fileManagerBean.sendReceipt(emailAddress, receipt.getId());
            System.out.println("email address: "+emailAddress);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Sent successfully", "sent successfully"));
        }
        return null;
    }
    
    public FileUploadManagerBean getFileManagerBean() {
        return fileManagerBean;
    }

    public void setFileManagerBean(FileUploadManagerBean fileManagerBean) {
        this.fileManagerBean = fileManagerBean;
    }
}
